package com.kdtech.analyse.outside;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import com.kdtech.analyse.AnalyseNews;
import com.kdtech.analyse.JSoupUtils;
import com.kdtech.crawler.CrawlHTML;

import com.kdtech.crawler.at.UrlArgumentTop;
import com.kdtech.entity.crawler.UrlMeta;
import com.kdtech.entity.data.NewsMeta;
import com.kdtech.utils.DateUtils;
import com.kdtech.utils.HtmlCleaner;
import com.kdtech.utils.RegexUtils;
import com.kdtech.utils.StringUtils;

/**
 * @author KK
 *
 */
public class UyghuramericanAnalyse implements AnalyseNews {

	private static final String[] regex={
		"http://forum.uyghuramerican.org/forum/showthread.php\\?[0-9]*.*",
		"http://uyghuramerican.org/article/[0-9a-zA-Z\\-\\.]*",
	};

	
	public boolean isDetailPage(String url) {
		return RegexUtils.matchAnyIgnoreCase(url, regex);
	}

	
	public NewsMeta parserHtml(UrlMeta urlMeta) {
		NewsMeta news=new NewsMeta();
		if (urlMeta.getHtml() == null) {
		}
		String htmltxt=urlMeta.getHtml();
		String url=urlMeta.getUrl();

		news.setUrl(url);
		String title=null;
		String content=null;
		String author=null;
		Long date=null;
		Document doc=Jsoup.parse(htmltxt);
		if(url.startsWith("http://forum.uyghuramerican.org/")){
			title =doc.select("title").text();
			content=HtmlCleaner.getContentHtml(url,doc.select(".postcontent"));
			String dateStr=doc.select(".postdate").text();
			if(dateStr!=null){
				String yearmonthday=StringUtils.substringBefore(dateStr, ",");
				if(yearmonthday!=null){
					String[] split=yearmonthday.split("-");
					yearmonthday="";
					for (int i=split.length-1; i >=0; i--) {
						yearmonthday +=split[i]+"-";
					}
					dateStr=yearmonthday +  StringUtils.substringAfter(dateStr, ",");
					date =DateUtils.matchDate(dateStr);
				}
			}
			if (date==null)date =DateUtils.matchDate(doc.select(".postdate").text());
			news.setTitle(StringUtils.trimSpace(title));
			news.setContent(content);
			news.setAuthor(author);
			news.setDate(date);
		}else{
			title =doc.select(".post-title").text();
			content=HtmlCleaner.getContentHtml(url,doc.select(".field-item"));
			if (date==null)date =DateUtils.matchDate(doc.select(".date").text());
			news.setTitle(StringUtils.trimSpace(title));
			news.setContent(content);
			news.setAuthor(author);
			news.setDate(date);
		}

		return news;
	}

	

	

	
}
